﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Process;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Supplieries
{
    /// <summary>
    /// 添加供应商
    /// </summary>
    public class CreateSupplierHandler : IRequestHandler<CreateSupplierCommand, Result>
    {
        /// <summary>
        /// mapper类
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IBaseRepository<Suppliers> _supplierRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateSupplierHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="supplierRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public CreateSupplierHandler(IBaseRepository<Suppliers> supplierRepository,
                                     ILogger<CreateSupplierHandler> logger,
                                     IMapper mapper)
        {
            _supplierRepository = supplierRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加供应商
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateSupplierCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //查询编码与名称是否存在
                var model = await (await _supplierRepository.GetAll()).Where(x => x.SupplierCoding == request.SupplierCoding || x.SupplierName == request.SupplierName).CountAsync();
                //判断如果存在提醒
                if (model > 0)
                {
                    result.Msg = "编码或名称已存在,请重新输入";
                }
                else
                {
                    //Mapper转换
                    var supplier = _mapper.Map<Suppliers>(request);
                    var res = await _supplierRepository.Add(supplier);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "添加供应商成功";
                    }
                }

            }
            catch (Exception ex)
            {
                result.Msg = "添加供应商异常" + ex.Message;
                _logger.LogError("添加供应商异常" + ex.Message);
            }
            return result;
        }
    }
}
